package com.bops.web.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.bops.biz.permission.Role;
import com.bops.biz.permission.RoleGroup;
import com.bops.dal.user.dataobject.RenyuaninfoDO;
import com.bops.dal.user.dataobject.RoleDO;
import com.bops.dal.user.dataobject.UsersDO;
import com.bops.dal.user.queryobject.RoleQuery;
import com.bops.service.CommonServiceLocator;
import com.bops.service.RoleService;
import com.bops.service.UserService;
import com.bops.web.ViewTools;
import com.yue.commons.seine.web.annotations.ControllerAction;
import com.yue.commons.seine.web.servlet.mvc.AbstractController;
import com.yue.commons.seine.web.servlet.result.Forward;
import com.yue.commons.seine.web.servlet.result.View;
import com.yue.commons.seine.web.servlet.result.WebResult;

public class RoleController extends AbstractController {

    private UserService userService = CommonServiceLocator.getUserService();
    private RoleService roleService = CommonServiceLocator.getRoleService();

    private List<UsersDO> getAllUsersList() {
        List<RenyuaninfoDO> tmpUserList = userService.listRenyuaninfo(null);
        List<UsersDO> allUserList = new ArrayList<UsersDO>();
        if (tmpUserList == null) {
            return allUserList;
        }
        for (RenyuaninfoDO r : tmpUserList) {
            UsersDO usersDO = new UsersDO();
            usersDO.setName(r.getEngineer());
            usersDO.setDep(r.getDepartment());
            usersDO.setCompany(r.getCompany());
            usersDO.setId(r.getId());
            allUserList.add(usersDO);
        }
        return allUserList;
    }


    @ControllerAction
    public WebResult step3(Map<String, Object> model, String[] selectUserRole, String[] oldSelectUserRole,
                           Integer[] userID, String[] groups, String roleGroup) {
        Map<String, String> selectMap = new HashMap<String, String>();
        if (selectUserRole != null) {
            for (String selectUser : selectUserRole) {
                selectMap.put(selectUser, selectUser);
            }
        }
        List<RoleDO> delList = new ArrayList<RoleDO>();
        List<RoleDO> addList = new ArrayList<RoleDO>();
        if (oldSelectUserRole != null) {
            for (String oldSelectUser : oldSelectUserRole) {
                if (oldSelectUser != null) {
                    int index = oldSelectUser.lastIndexOf("__");
                    String key = oldSelectUser.substring(0, index);
                    String flagTxt = oldSelectUser.substring(index + 2);
                    boolean oldContain = false;
                    if ("yes".equalsIgnoreCase(flagTxt)) {
                        oldContain = true;
                    }
                    boolean contain = selectMap.containsKey(key);
                    if (oldContain && !contain) // 原先有，现在没有，那么就是删除
                    {
                        RoleDO usrDO = convertUserRoleDO(key);
                        if (usrDO != null) {
                            delList.add(usrDO);
                        }
                    } else if (!oldContain && contain) // 原先没有，现在有，那么就是添加
                    {
                        RoleDO usrDO = convertUserRoleDO(key);
                        if (usrDO != null) {
                            addList.add(usrDO);
                        }
                    }
                }

            }
            roleService.batchUpdateRole(addList, delList);
            model.put("MESSAGE", "保存成功!" + ViewTools.formatSimpleDateNull(new Date()));
        }
        return step2(model, userID, groups, roleGroup);
    }

    private static RoleDO convertUserRoleDO(String str) {
        if (str == null) {
            return null;
        }
        try {
            String[] sp = str.split("__");
            String roleName = sp[0];
            String userIDTxt = sp[1];
            int userID = Integer.valueOf(userIDTxt).intValue();
            RoleDO userDO = new RoleDO();
            userDO.setUsersId(userID);
            userDO.setRoleName(roleName);
            userDO.setStatus(RoleDO.ENABLED);
            return userDO;
        } catch (Exception e) {
            return null;
        }
    }

//    
//    @ControllerAction
//    public WebResult step2(Map<String, Object> model, Integer[] userID, Integer type) {
//
//        model.put("type", type);
//        if (userID == null || userID.length == 0) {
//            model.put("errorMsg", "错误！没有选择用户！");
//            return new Forward("/bops/role/step1.htm");
//        }
//        List<Integer> userIdList = new ArrayList<Integer>();
//        for (int id : userID) {
//            userIdList.add(id);
//        }
//        RoleQuery roleQuery = new RoleQuery();
//        roleQuery.setStatus(RoleDO.ENABLED);
//        roleQuery.setUsersIdList(userIdList);
//        List<RoleDO> userRoleDBList = roleService.listRole(roleQuery);
//        List<Role> roleList = roleService.getAllRoleList();
//
//        List<RoleUserInfo> roleUserInfoList = new ArrayList<RoleUserInfo>();
//        if (roleList != null) {
//            for (Role role : roleList) {
//                String roleName = role.getName();
//                String groupName = role.getGroup();
//                if (checkFilterPermisson(type, groupName)) {
//                    continue;
//                }
//                String roleId = role.getId();
//                RoleUserInfo tmpRoleUserInfo = new RoleUserInfo(roleName, roleId, userIdList);
//                roleUserInfoList.add(tmpRoleUserInfo);
//                for (Integer userId : userIdList) {
//                    boolean flag = false;
//                    if (userRoleDBList != null) {
//                        for (RoleDO tmpUserRoleDO : userRoleDBList) {
//                            Integer tmpUserId = tmpUserRoleDO.getUsersId();
//                            if (tmpUserId != null && tmpUserId.intValue() == userId.intValue()
//                                && roleId.equalsIgnoreCase(tmpUserRoleDO.getRoleName())) {
//                                flag = true;
//                                break;
//                            }
//                        }
//                    }
//                    tmpRoleUserInfo.addFlag(flag);
//                }
//            }
//        }
//        model.put("roleUserInfoList", roleUserInfoList);
//        model.put("userIdList", userIdList);
//        return new View("/role/step2.htm");
//    }

    
    @ControllerAction
    public WebResult step2(Map<String, Object> model, Integer[] userID, String[] groups, String roleGroup) {
        model.put("groups", groups);
        model.put("roleGroup", roleGroup);
        if (userID == null || userID.length == 0) {
            model.put("errorMsg", "错误！没有选择用户！");
            return new Forward("/role/step1.htm");
        }
        if ((groups == null || groups.length == 0) && StringUtils.isEmpty(roleGroup)) {
            model.put("errorMsg", "错误！请选择要分配的权限！");
            return new Forward("/role/step1.htm");
        }
        List<Integer> userIdList = new ArrayList<Integer>();
        for (int id : userID) {
            userIdList.add(id);
        }
        RoleQuery roleQuery = new RoleQuery();
        roleQuery.setStatus(RoleDO.ENABLED);
        roleQuery.setUsersIdList(userIdList);
        List<RoleDO> userRoleDBList = roleService.listRole(roleQuery);
        List<Role> roleList = roleService.getAllRoleList();
        List<RoleGroup> roleGroups = roleService.getRoleGroups();
        RoleGroup rg = roleService.getRoleGroup(roleGroup);
        Map<String, List<RoleUserInfo>> roleUserInfoMap = new HashMap<String, List<RoleUserInfo>>();
        if (roleList != null) {
            for (Role role : roleList) {
                String roleName = role.getName();
                String groupName = role.getGroup();
                if (rg != null) {
                    groupName = rg.getName();
                    if (!rg.hasRole(roleName)) {
                        continue;
                    }
                } else {
                    if (!checkFilterPermisson(groups, groupName)) {
                        continue;
                    }
                }
                List<RoleUserInfo> roleUserInfoList = roleUserInfoMap.get(groupName);
                if (roleUserInfoList == null) {
                    roleUserInfoList = new ArrayList<RoleUserInfo>();
                    roleUserInfoMap.put(groupName, roleUserInfoList);
                }
                String roleId = role.getId();
                RoleUserInfo tmpRoleUserInfo = new RoleUserInfo(roleName, roleId, userIdList);
                roleUserInfoList.add(tmpRoleUserInfo);
                for (Integer userId : userIdList) {
                    boolean flag = false;
                    if (userRoleDBList != null) {
                        for (RoleDO tmpUserRoleDO : userRoleDBList) {
                            Integer tmpUserId = tmpUserRoleDO.getUsersId();
                            if (tmpUserId != null && tmpUserId.intValue() == userId.intValue()
                                && roleId.equalsIgnoreCase(tmpUserRoleDO.getRoleName())) {
                                flag = true;
                                break;
                            }
                        }
                    }
                    tmpRoleUserInfo.addFlag(flag);
                }
            }
        }
        model.put("roleUserInfoMap", roleUserInfoMap);
        model.put("userIdList", userIdList);
        model.put("roleGroups", roleGroups);
        return new View("/role/step2.htm");
    }
    
    /**
     * 判断type和权限组是否相同
     * 
     * @param type
     * @param groupName
     * @return
     */
    private boolean checkFilterPermisson(String[] groups, String groupName) {
        if (StringUtils.isEmpty(groupName) || groups == null || groups.length == 0) {
            return false;
        }
        for (String group : groups) {
            if (groupName.equals(group)) {
                return true;
            }
        }
        return false;
    }

    @ControllerAction
    public WebResult step1(Map<String, Object> model) {
        List<UsersDO> allUserList = getAllUsersList();
        List<GroupUser> groupUserList = new ArrayList<GroupUser>();
        if (allUserList != null) {
            for (UsersDO tmpUser : allUserList) {
                GroupUser tmpGroupUser = null;
             
                for (GroupUser groupUser : groupUserList) {
                    if (groupUser.getDep()!=null && groupUser.getCompany()!=null && groupUser.getDep().equalsIgnoreCase(tmpUser.getDep())
                        && groupUser.getCompany().equalsIgnoreCase(tmpUser.getCompany())) {
                        tmpGroupUser = groupUser;
                        break;
                    }
                }
                if (tmpGroupUser == null) {
                    tmpGroupUser = new GroupUser(tmpUser.getCompany(), tmpUser.getDep(), tmpUser.getId());
                    groupUserList.add(tmpGroupUser);
                }
                tmpGroupUser.addUser(tmpUser);
            }
        }
        for (GroupUser groupUser : groupUserList) {
            groupUser.calc();
        }
        Collections.sort(groupUserList);

        model.put("groupUserList", groupUserList);
       // model.put("PERMISSION_ARRAY", PERMISSION_ARRAY);
        
         
        List<List<String>> allGroups = new ArrayList<List<String>>();
        List<String> permissionGroup = getPermissionGroup();
        List<RoleGroup> roleGroups = getRoleGroups();
        int size = permissionGroup.size();
        List<String> group = null;
        int num = 10;
        for (int i = 0; i < size; i++) {
            if (i % num == 0) {
                group = new ArrayList<String>(num);
                allGroups.add(group);
            }
            group.add(i % num, permissionGroup.get(i));
        }
        if (group != null && group.size() < num) {
            for (int i = group.size(); i < num; i++) {
                group.add(null);
            }
        }
        model.put("allGroups", allGroups);
        model.put("roleGroups", roleGroups);
        return new View("/role/step1.htm");
    }

    private List<String> getPermissionGroup() {
        List<String> list = new ArrayList<String>();
        
        for (String[] ps : PERMISSION_ARRAY) {
            list.add(ps[1]);
        }
        return list;
    }

    private List<RoleGroup> getRoleGroups() {
         return roleService.getRoleGroups();
    }

    
    public static class GroupUser implements Comparable<GroupUser> {

        private String             dep;
        private String             company;
        private Integer            id;
        private List<UsersDO>      userList    = new ArrayList<UsersDO>();
        private List<List<Object>> userListSet = new ArrayList<List<Object>>();

        public GroupUser(String company, String dep, Integer id) {
            this.company = company;
            this.dep = dep;
            this.id = id;
        }

        public String getDep() {
            return dep;
        }

        public String getCompany() {
            return company;
        }

        public Integer getId() {
            return id;
        }

        public void addUser(UsersDO user) {
            userList.add(user);
        }

        public void calc() {
            int EACH = 50;
            int mod = 0;
            List<Object> sonUserList = null;
            for (int i = 0; i < userList.size(); i++) {
                mod = i % EACH;
                if (mod == 0) {
                    sonUserList = new ArrayList<Object>();
                }
                sonUserList.add(userList.get(i));
                if (mod == EACH - 1) {
                    userListSet.add(sonUserList);
                }
            }
            for (int i = mod + 1; i < EACH; i++) {
                sonUserList.add(NULL_OBJ);
                if (i == EACH - 1) {
                    userListSet.add(sonUserList);
                }
            }
        }

        public List<List<Object>> getUserListSet() {
            return userListSet;
        }

        public int getSonRowCount() {
            return userListSet.size();
        }

        public int compareTo(GroupUser arg0) {
        	System.out.println(getCompany());
            if (getCompany().compareToIgnoreCase(arg0.getCompany()) == 0) {
                return getDep().compareToIgnoreCase(arg0.getDep());
            }
            return getCompany().compareToIgnoreCase(arg0.getCompany());
        }
    }

    public static class RoleUserInfo {

        private String        roleName;
        private String        roleId;
        // 用户是否有权限,该List和userIdList一一对应
        private List<Boolean> userFlagList = new ArrayList<Boolean>();
        List<Integer>         userIdList   = null;

        public RoleUserInfo(String roleName, String roleId, List<Integer> userIdList) {
            this.roleName = roleName;
            this.roleId = roleId;
            this.userIdList = userIdList;
        }

        public void addFlag(boolean flag) {
            userFlagList.add(flag);
        }

        public boolean isHasRole(int velocityIndex) {
            velocityIndex = velocityIndex - 1;
            if (velocityIndex >= 0 && velocityIndex < userFlagList.size()) {
                return userFlagList.get(velocityIndex);
            }
            return false;
        }
 
        public String getRoleName() {
            return roleName;
        }

        public String getRoleId() {
            return roleId;
        }
    }

    private final static Object NULL_OBJ         = new Object();

    // 组权限名称必须和spring_permission_*.xml文件中的group名字一样
    private static String[][]   PERMISSION_ARRAY = { { "1", "人员信息管理" }, { "2", "产品管理" },
            { "3", "订单管理" }, { "4", "服务管理" }, { "5", "客户服务" }, { "6", "咨询中心" }, { "7", "综合管理" }           };

}
